<template>
  <XLayoutMain>
    <div class="g-content">
      <x-data-table
        ref="tableRef"
        v-model:checked-row-keys="checkedRowKeys"
        v-model:immediate="immediate"
        :row-key="(row) => row.adgroupId"
        :params="paginationParams"
        :columns="columns"
      >
        <template #tableTitle>
          <n-space :size="20">
            <div> <n-text :depth="3">上传提交时间：</n-text> {{ query.submitTime }} </div>
            <div> <n-text :depth="3">公司名称：</n-text>{{ query.customerName }} </div>
            <div> <n-text :depth="3">账户ID：</n-text>{{ query.accountCode }} </div>
          </n-space>
          <x-form ref="formRef" v-model:model="form" style="margin-top: 10px" inline wrap label-placement="left">
            <n-form-item label="上传状态">
              <n-select v-model:value="form.uploadStatus" placeholder="请选择" :options="uploadStatusList" clearable />
            </n-form-item>
            <x-button type="primary" @click="handleSubmit">查询</x-button>
            <x-button @click="handleRefresh">重置</x-button>
            <x-button type="primary" :disabled="checkedRowKeys.length === 0" @click="handleUpload">批量上传</x-button>
            <x-button type="primary" @click="handleUploadAllError">失败广告全部重传</x-button>
            <x-button type="primary" :disabled="checkedRowKeys.length === 0" @click="handleCopyMore">批量复制</x-button>
          </x-form>
        </template>
      </x-data-table>
    </div>

    <template #footer>
      <n-button @click="handleBack">返回</n-button>
    </template>
  </XLayoutMain>
</template>

<script setup lang="ts">
  import { XLayoutMain, XDataTable, XButton } from '@/components'
  import { NButton, NTag, NSpace, NText, useDialog, NFormItem, NSelect, NPopover } from 'naive-ui'
  import { useStore } from '@/store'
  import { useRoute, useRouter } from 'vue-router'
  import { computed, ref, h, VNode } from 'vue'
  import { useActivated } from '@/hooks'
  import { ManageRecordDetailModel } from '@/api/model/intelligentModel'
  import XForm from '@/components/x-form/index.vue'

  const store = useStore()
  const router = useRouter()
  const route = useRoute()
  const dialog = useDialog()
  const tableRef = ref(null)
  const form = ref({
    uploadStatus: null
  })
  const formRef = ref(null)
  const uploadStatusList = ref([
    {
      value: 1,
      label: '上传成功'
    },
    {
      value: 2,
      label: '上传失败'
    }
  ])
  const immediate = ref(true)
  const query = route.query
  const checkedRowKeys = ref([])
  const paginationParams = computed(() => {
    return {
      actions: 'intelligent/adgroupRecordList',
      data: {
        adgroupUploadId: route.query.id,
        uploadStatus: form.value.uploadStatus
      }
    }
  })
  const columns = ref([
    {
      type: 'selection'
    },
    {
      key: 'adgroupName',
      title: '广告名称'
    },
    {
      key: 'uploadStatus',
      title: '状态',
      render(row: any): VNode | null {
        return row.uploadStatus === 1
          ? h(NTag, { type: 'success', bordered: false }, () => '上传成功')
          : row.uploadStatus === 2
          ? h(NPopover, null, {
              trigger: () => h(NTag, { type: 'error', bordered: false }, () => '上传失败'),
              default: () => row.failureReason
            })
          : h(NTag, { type: 'warning', bordered: false }, () => '上传中')
      }
    },
    {
      key: 'action-1',
      title: '操作',
      render(row: any): VNode {
        return h(NSpace, {}, () => [
          row.uploadStatus === 2 &&
            h(
              NButton,
              { type: 'primary', loading: row.loading, text: true, onClick: () => handleRetry(row) },
              () => '再次上传'
            ),
          h(NButton, { type: 'primary', text: true, onClick: () => handleCopy(row) }, () => '复制'),
          row.uploadStatus === 2 &&
            h(NButton, { type: 'primary', text: true, onClick: () => handleEdit(row) }, () => '修改')
        ])
      }
    }
  ])

  useActivated(() => {
    handleRefresh()
  })
  function handleSubmit() {
    immediate.value = true
  }
  function handleRefresh() {
    checkedRowKeys.value = []
    formRef.value.resetFields()
    handleSubmit()
  }

  async function handleRetry(row: ManageRecordDetailModel) {
    row.loading = true
    const params = {
      batchId: query.batchId,
      adgroupIdList: [row.adgroupId]
    }
    await store.dispatch('intelligent/uploadAdgroup', params).finally(() => {
      row.loading = false
    })
    handleRefresh()
  }

  // 单个复制
  async function handleCopy(row: any) {
    const params = {
      adgroupIdList: [row.adgroupId]
    }
    const { data } = await store.dispatch('intelligent/adgroupCopy', params)

    if (data) {
      router.push({
        name: 'IntelCreateList',
        query: {
          accountCode: query.accountCode,
          accountName: query.customerName,
          batchId: data
        }
      })
    }
  }
  // 批量复制
  async function handleCopyMore() {
    const params = {
      adgroupIdList: checkedRowKeys.value,
      adgroupUploadId: query.id
    }
    const { data } = await store.dispatch('intelligent/adgroupCopy', params)

    if (data) {
      router.push({
        name: 'IntelCreateList',
        query: {
          accountCode: query.accountCode,
          accountName: query.customerName,
          batchId: data
        }
      })
    }
  }
  // 批量上传
  async function handleUpload() {
    const params = {
      batchId: query.batchId,
      adgroupIdList: checkedRowKeys.value
    }
    store.dispatch('intelligent/uploadAdgroup', params).then(() => {
      immediate.value = true
    })
  }
  // 失败广告全部重传
  async function handleUploadAllError() {
    const params = {
      adgroupUploadId: query.id
    }
    store.dispatch('intelligent/uploadAdgroup', params).then(() => {
      immediate.value = true
    })
  }
  function handleEdit(row: any) {
    router.push({
      name: 'AdsCreate',
      query: {
        adgroupId: row.adgroupId,
        batchId: query.batchId,
        type: 'edit'
      }
    })
  }

  function handleBack() {
    router.back()
  }
</script>

<style scoped lang="scss"></style>
